package com.xgit.iov.codegen.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgit.iov.codegen.entity.GenTable;
import com.xgit.iov.codegen.service.IGenTableService;
import com.xgit.iov.common.core.util.R;
import com.xgit.iov.common.log.annotation.LogAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 */

@RestController
@RequestMapping("/generator")
public class GenController {

    @Autowired
    private IGenTableService genTableService;

    /**
     * 查询代码生成列表
     */
    @GetMapping("/page")
    public R page(Page page, GenTable genTable) {
        return R.ok(genTableService.selectGenTablePage(page, genTable));
    }

    /**
     * 获取代码
     */
    @GetMapping(value = "/{id}")
    public R getById(@PathVariable Long id) {
        GenTable table = genTableService.selectGenTableById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", table.getColumns());
        return R.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    public R dataList(Page page, GenTable genTable) {
        return R.ok(genTableService.selectDbTablePage(page, genTable));
    }

    /**
     * 导入表结构（保存）
     */
	@LogAnnotation("导入表结构")
    @PostMapping("/importTable")
    public R importTableSave(String tables, String dataSource) {
        String[] tableNames = Convert.toStrArray(tables);
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames,dataSource);
        genTableService.importGenTable(tableList, dataSource);
        return R.ok("导入成功");
    }

    /**
     * 修改保存代码生成业务
     */
	@LogAnnotation("修改代码生成")
    @PutMapping("/update")
    public R update(@RequestBody GenTable genTable) {
        genTableService.updateGenTable(genTable);
        return R.ok("操作成功");
    }

    @DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids) {
        genTableService.deleteGenTableByIds(ids);
        return R.ok("操作成功");
    }

    /**
     * 预览代码
     */

    @GetMapping("/preview/{id}")
    public R preview(@PathVariable("id") Long id) {
        Map<String, String> dataMap = genTableService.previewCode(id);
        return R.ok(dataMap);
    }

    /**
     * 生成代码
     */
	@LogAnnotation("生成代码")
    @GetMapping("/genCode/{tableNames}")
    public R genCode(@PathVariable String[] tableNames) {
       List<String> tableNameList = CollUtil.toList(tableNames);
       for (String tableName : tableNameList){
            genTableService.generatorCode(tableName);
       }
       return R.ok("操作成功");
    }

}
